"""
DDL操作符实现
包含CREATE TABLE、DROP TABLE等DDL操作
"""

from typing import Optional, List, Dict, Any, Iterator
import time

from ..executor_base import IteratorExecutor
from ..types import (
    Record, RecordBatch, ExecutionContext, OperatorType,
    ColumnInfo, DataType
)
from ..storage_adapter import StorageEngineAdapter
from OperatingSystem.table_schema import Column, ColumnType


class CreateTableOperator(IteratorExecutor):
    """CREATE TABLE操作符"""
    
    def __init__(self, executor_id: str, context: ExecutionContext,
                 table_name: str, columns: List[Dict[str, Any]],
                 storage_engine: StorageEngineAdapter = None):
        super().__init__(executor_id, context)
        self.table_name = table_name
        self.columns = columns
        self.storage_engine = storage_engine
        self.executed = False
        self.success = False
    
    def open(self):
        """打开CREATE TABLE操作符"""
        with self.lock:
            if self.is_open:
                return
            
            self.is_open = True
            self.current_iterator = self._create_ddl_iterator()
            
            # 更新统计信息
            self.update_stats(io_ops=1)
    
    def _create_ddl_iterator(self) -> Iterator[Record]:
        """创建DDL执行迭代器"""
        if self.executed:
            return
        
        self.executed = True
        
        try:
            if self.storage_engine:
                # 转换列定义为 OperatingSystem 格式
                os_columns = []
                for col_def in self.columns:
                    col_type = self._convert_to_os_column_type(col_def.get('type', 'VARCHAR'))
                    length = col_def.get('length', 255 if col_type in [ColumnType.VARCHAR, ColumnType.CHAR] else None)
                    
                    os_column = Column(
                        name=col_def.get('name', ''),
                        column_type=col_type,
                        length=length,
                        nullable=col_def.get('nullable', True),
                        primary_key=col_def.get('primary_key', False),
                        default_value=col_def.get('default_value')
                    )
                    os_columns.append(os_column)
                
                # 创建表 - 使用适配器的方法，传递转换后的os_columns
                self.success = self.storage_engine.create_table(self.table_name, os_columns)
                
                # 返回执行结果
                result = {
                    "operation": "CREATE TABLE",
                    "table_name": self.table_name,
                    "success": self.success,
                    "message": f"Table '{self.table_name}' created successfully" if self.success 
                              else f"Failed to create table '{self.table_name}'"
                }
            else:
                # 模拟执行
                self.success = True
                result = {
                    "operation": "CREATE TABLE",
                    "table_name": self.table_name,
                    "success": True,
                    "message": f"Table '{self.table_name}' created (simulated)"
                }
            
            # 更新统计
            self.update_stats(rows_processed=1)
            
            yield result
            
        except Exception as e:
            self.success = False
            print(f"[CreateTableOperator] 创建表 {self.table_name} 时发生异常: {e}")
            import traceback
            traceback.print_exc()
            error_result = {
                "operation": "CREATE TABLE",
                "table_name": self.table_name,
                "success": False,
                "message": f"Failed to create table '{self.table_name}': {str(e)}",
                "error": str(e)
            }
            yield error_result
    
    def _convert_to_os_column_type(self, type_str: str) -> ColumnType:
        """转换为 OperatingSystem 的列类型"""
        type_str = type_str.upper()
        
        if type_str in ['INT', 'INTEGER']:
            return ColumnType.INT
        elif type_str in ['FLOAT', 'REAL', 'DOUBLE']:
            return ColumnType.FLOAT
        elif type_str in ['VARCHAR', 'STRING', 'TEXT']:
            return ColumnType.VARCHAR
        elif type_str in ['CHAR']:
            return ColumnType.CHAR
        elif type_str in ['BOOLEAN', 'BOOL']:
            return ColumnType.BOOLEAN
        elif type_str in ['DATE', 'TIMESTAMP', 'DATETIME']:
            return ColumnType.DATE
        else:
            return ColumnType.VARCHAR  # 默认类型
    
    def close(self):
        """关闭CREATE TABLE操作符"""
        with self.lock:
            if not self.is_open:
                return
            
            self.is_open = False
            self.current_iterator = None
            
            # 更新最终统计
            self.stats.execution_time_ms = (time.time() - self.context.start_time) * 1000
    
    def get_estimated_cost(self) -> float:
        """获取估算成本"""
        return 1.0  # DDL操作成本固定
    
    def get_estimated_rows(self) -> int:
        """获取估算行数"""
        return 1  # DDL操作返回1行结果


class DropTableOperator(IteratorExecutor):
    """DROP TABLE操作符"""
    
    def __init__(self, executor_id: str, context: ExecutionContext,
                 table_name: str, storage_engine: StorageEngineAdapter = None):
        super().__init__(executor_id, context)
        self.table_name = table_name
        self.storage_engine = storage_engine
        self.executed = False
        self.success = False
    
    def open(self):
        """打开DROP TABLE操作符"""
        with self.lock:
            if self.is_open:
                return
            
            self.is_open = True
            self.current_iterator = self._create_ddl_iterator()
            
            # 更新统计信息
            self.update_stats(io_ops=1)
    
    def _create_ddl_iterator(self) -> Iterator[Record]:
        """创建DDL执行迭代器"""
        if self.executed:
            return
        
        self.executed = True
        
        try:
            if self.storage_engine:
                # 删除表
                self.success = self.storage_engine.drop_table(self.table_name)
                
                # 返回执行结果
                result = {
                    "operation": "DROP TABLE",
                    "table_name": self.table_name,
                    "success": self.success,
                    "message": f"Table '{self.table_name}' dropped successfully" if self.success 
                              else f"Failed to drop table '{self.table_name}'"
                }
            else:
                # 模拟执行
                self.success = True
                result = {
                    "operation": "DROP TABLE",
                    "table_name": self.table_name,
                    "success": True,
                    "message": f"Table '{self.table_name}' dropped (simulated)"
                }
            
            # 更新统计
            self.update_stats(rows_processed=1)
            
            yield result
            
        except Exception as e:
            self.success = False
            error_result = {
                "operation": "DROP TABLE",
                "table_name": self.table_name,
                "success": False,
                "error": str(e)
            }
            yield error_result
    
    def close(self):
        """关闭DROP TABLE操作符"""
        with self.lock:
            if not self.is_open:
                return
            
            self.is_open = False
            self.current_iterator = None
            
            # 更新最终统计
            self.stats.execution_time_ms = (time.time() - self.context.start_time) * 1000
    
    def get_estimated_cost(self) -> float:
        """获取估算成本"""
        return 1.0  # DDL操作成本固定
    
    def get_estimated_rows(self) -> int:
        """获取估算行数"""
        return 1  # DDL操作返回1行结果


class InsertOperator(IteratorExecutor):
    """INSERT操作符"""
    
    def __init__(self, executor_id: str, context: ExecutionContext,
                 table_name: str, values: List[Dict[str, Any]],
                 storage_engine: StorageEngineAdapter = None):
        super().__init__(executor_id, context)
        self.table_name = table_name
        self.values = values
        self.storage_engine = storage_engine
        self.executed = False
        self.success_count = 0
    
    def open(self):
        """打开INSERT操作符"""
        with self.lock:
            if self.is_open:
                return
            
            self.is_open = True
            self.current_iterator = self._create_insert_iterator()
            
            # 更新统计信息
            self.update_stats(io_ops=1)
    
    def _create_insert_iterator(self) -> Iterator[Record]:
        """创建INSERT执行迭代器"""
        if self.executed:
            return
        
        self.executed = True
        
        try:
            print(f"[DEBUG INSERT] 表:{self.table_name}, 数据:{self.values}, 存储引擎:{self.storage_engine is not None}")
            if self.storage_engine:
                # 将列名-值对列表转换为单个记录
                record = {}
                for item in self.values:
                    if isinstance(item, dict) and 'column' in item and 'value' in item:
                        record[item['column']] = item['value']
                
                print(f"[DEBUG INSERT] 转换后记录:{record}")
                
                if record:  # 只有当记录不为空时才插入
                    print(f"[DEBUG INSERT] 调用插入...")
                    success = self.storage_engine.insert_record(self.table_name, record)
                    print(f"[DEBUG INSERT] 插入成功:{success}")
                    if success:
                        self.success_count += 1
                else:
                    print(f"[DEBUG INSERT] 记录为空，跳过插入")
            else:
                print(f"[DEBUG INSERT] 存储引擎为None，走模拟路径")
                # 模拟执行
                self.success_count = 1 if self.values else 0
            
            # 生成执行结果
            result = {
                "operation": "INSERT",
                "table_name": self.table_name,
                "inserted_rows": self.success_count,
                "total_rows": 1,  # 现在是单条记录插入
                "success": self.success_count > 0,
                "message": f"Inserted {self.success_count} row into '{self.table_name}'"
            }
            
            # 更新统计
            self.update_stats(rows_processed=self.success_count)
            
            yield result
            
        except Exception as e:
            error_result = {
                "operation": "INSERT",
                "table_name": self.table_name,
                "inserted_rows": self.success_count,
                "total_rows": 1,  # 现在是单条记录插入
                "success": False,
                "error": str(e)
            }
            yield error_result
    
    def close(self):
        """关闭INSERT操作符"""
        with self.lock:
            if not self.is_open:
                return
            
            self.is_open = False
            self.current_iterator = None
            
            # 更新最终统计
            self.stats.execution_time_ms = (time.time() - self.context.start_time) * 1000
    
    def get_estimated_cost(self) -> float:
        """获取估算成本"""
        return len(self.values) * 0.5  # 每条记录0.5个成本单位
    
    def get_estimated_rows(self) -> int:
        """获取估算行数"""
        return 1  # INSERT操作返回1行结果（执行摘要）


class UpdateOperator(IteratorExecutor):
    """UPDATE操作符"""
    
    def __init__(self, executor_id: str, context: ExecutionContext,
                 table_name: str, set_clauses: List[Dict[str, Any]], 
                 where_condition: str = None,
                 storage_engine: StorageEngineAdapter = None):
        super().__init__(executor_id, context)
        self.table_name = table_name
        self.set_clauses = set_clauses  # [{'column': 'name', 'value': 'new_value'}]
        self.where_condition = where_condition
        self.storage_engine = storage_engine
        self.executed = False
        self.updated_count = 0
    
    def open(self):
        """打开UPDATE操作符"""
        with self.lock:
            if self.is_open:
                return
            
            self.is_open = True
            self.current_iterator = self._create_update_iterator()
            
            # 更新统计信息
            self.update_stats(io_ops=1)
    
    def _create_update_iterator(self) -> Iterator[Record]:
        """创建UPDATE执行迭代器"""
        if self.executed:
            return
        
        self.executed = True
        
        try:
            if self.storage_engine:
                # 使用真实存储引擎执行UPDATE
                # 构建更新条件和更新内容
                condition = {}
                updates = {}
                
                # 解析WHERE条件（简化实现）
                if self.where_condition:
                    condition = self._parse_where_condition(self.where_condition)
                
                # 构建更新内容
                for set_clause in self.set_clauses:
                    column = set_clause['column']
                    value = set_clause['value']
                    is_expression = set_clause.get('is_expression', False)
                    
                    if is_expression:
                        # 处理算术表达式
                        updates[column] = {'$expression': value}
                    else:
                        updates[column] = value
                
                # 执行更新
                self.updated_count = self.storage_engine.update_records(
                    self.table_name, condition, updates
                )
                
                # 如果没有更新任何记录，且条件中有数值，尝试用字符串类型再次匹配
                if self.updated_count == 0 and condition:
                    alternative_condition = self._create_alternative_condition(condition)
                    if alternative_condition and alternative_condition != condition:
                        print(f"[UPDATE] 第一次匹配失败，尝试替代条件: {alternative_condition}")
                        self.updated_count = self.storage_engine.update_records(
                            self.table_name, alternative_condition, updates
                        )
                
                result = {
                    "operation": "UPDATE",
                    "table_name": self.table_name,
                    "updated_rows": self.updated_count,
                    "success": True,  # UPDATE操作本身成功，即使更新行数为0
                    "message": f"Updated {self.updated_count} rows in '{self.table_name}'"
                }
            else:
                # 模拟执行
                self.updated_count = 1  # 模拟更新1行
                result = {
                    "operation": "UPDATE",
                    "table_name": self.table_name,
                    "updated_rows": self.updated_count,
                    "success": True,
                    "message": f"Updated {self.updated_count} rows in '{self.table_name}' (simulated)"
                }
            
            # 更新统计
            self.update_stats(rows_processed=self.updated_count)
            
            yield result
            
        except Exception as e:
            error_result = {
                "operation": "UPDATE",
                "table_name": self.table_name,
                "updated_rows": 0,
                "success": False,
                "error": str(e)
            }
            yield error_result
    
    def close(self):
        """关闭UPDATE操作符"""
        with self.lock:
            if not self.is_open:
                return
            
            self.is_open = False
            self.current_iterator = None
            
            # 更新最终统计
            self.stats.execution_time_ms = (time.time() - self.context.start_time) * 1000
    
    def get_estimated_cost(self) -> float:
        """获取估算成本"""
        return 2.0  # UPDATE操作成本相对较高（查询+修改）
    
    def get_estimated_rows(self) -> int:
        """获取估算行数"""
        return 1  # UPDATE操作返回1行结果（执行摘要）
    
    def _parse_where_condition(self, where_condition: str) -> Dict[str, Any]:
        """解析WHERE条件（支持多种比较操作符，包括LIKE）"""
        condition = {}
        try:
            # 处理LIKE操作符
            if ' LIKE ' in where_condition.upper():
                # 使用原始条件进行分割，保持字段名的原始大小写
                like_pos = where_condition.upper().find(' LIKE ')
                if like_pos != -1:
                    field = where_condition[:like_pos].strip()
                    pattern = where_condition[like_pos + 6:].strip().strip("'\"")
                    # 转换SQL LIKE模式为正则表达式
                    import re
                    regex_pattern = pattern.replace('%', '.*').replace('_', '.')
                    condition[field] = {"$regex": regex_pattern}
                    return condition
            
            # 支持的操作符，按长度降序排列以避免匹配冲突
            operators = ['>=', '<=', '!=', '=', '>', '<']
            
            for op in operators:
                if op in where_condition:
                    parts = where_condition.split(op, 1)  # 只分割第一个匹配
                    if len(parts) == 2:
                        field = parts[0].strip()
                        value = parts[1].strip().strip("'\"")
                        
                        # 尝试转换为数字
                        try:
                            value = int(value)
                        except ValueError:
                            try:
                                value = float(value)
                            except ValueError:
                                pass  # 保持字符串
                        
                        # 根据操作符构建存储引擎能理解的条件格式
                        if op == '=':
                            condition[field] = value
                        elif op == '>':
                            condition[field] = {"$gt": value}
                        elif op == '<':
                            condition[field] = {"$lt": value}
                        elif op == '>=':
                            condition[field] = {"$gte": value}
                        elif op == '<=':
                            condition[field] = {"$lte": value}
                        elif op == '!=':
                            condition[field] = {"$ne": value}
                        
                        break  # 找到第一个匹配的操作符就退出
                        
        except Exception as e:
            print(f"解析WHERE条件失败: {e}")
            import traceback
            traceback.print_exc()
        
        return condition
    
    def _create_alternative_condition(self, original_condition: Dict[str, Any]) -> Dict[str, Any]:
        """创建替代条件，用于处理数据类型不匹配的情况"""
        alternative_condition = {}
        
        for field, value in original_condition.items():
            # 如果是简单的等值条件，尝试转换数据类型
            if not isinstance(value, dict):  # 不是 {"$gt": ...} 这样的复杂条件
                if isinstance(value, int):
                    # 数字转字符串
                    alternative_condition[field] = str(value)
                elif isinstance(value, str) and value.isdigit():
                    # 纯数字字符串转整数
                    alternative_condition[field] = int(value)
                elif isinstance(value, str):
                    try:
                        # 尝试转换为浮点数
                        alternative_condition[field] = float(value)
                    except ValueError:
                        # 保持原值
                        alternative_condition[field] = value
                else:
                    # 其他类型保持原值
                    alternative_condition[field] = value
            else:
                # 复杂条件，尝试转换内部的值
                for op, op_value in value.items():
                    if isinstance(op_value, int):
                        alternative_condition[field] = {op: str(op_value)}
                    elif isinstance(op_value, str) and op_value.isdigit():
                        alternative_condition[field] = {op: int(op_value)}
                    else:
                        alternative_condition[field] = value
                    break  # 只处理第一个操作符
        
        return alternative_condition


class DeleteOperator(IteratorExecutor):
    """DELETE操作符"""
    
    def __init__(self, executor_id: str, context: ExecutionContext,
                 table_name: str, where_condition: str = None,
                 storage_engine: StorageEngineAdapter = None, child_executor=None):
        super().__init__(executor_id, context)
        self.table_name = table_name
        self.where_condition = where_condition
        self.storage_engine = storage_engine
        self.child_executor = child_executor
        self.executed = False
        self.deleted_count = 0
    
    def open(self):
        """打开DELETE操作符"""
        with self.lock:
            if self.is_open:
                return
            
            self.is_open = True
            self.current_iterator = self._create_delete_iterator()
            
            # 更新统计信息
            self.update_stats(io_ops=1)
    
    def _create_delete_iterator(self) -> Iterator[Record]:
        """创建DELETE执行迭代器"""
        if self.executed:
            return
        
        self.executed = True
        
        try:
            if self.storage_engine:
                # 使用真实存储引擎执行DELETE
                # 如果有子执行器，先通过子执行器找到需要删除的记录
                if self.child_executor:
                    # 打开子执行器
                    self.child_executor.open()
                    records_to_delete = []
                    
                    try:
                        # 获取所有匹配的记录
                        while True:
                            child_batch = self.child_executor.next_batch()
                            if not child_batch:
                                break
                            
                            for record in child_batch:
                                self.check_timeout()
                                records_to_delete.append(record)
                    finally:
                        # 关闭子执行器
                        self.child_executor.close()
                    
                    # 对于每条记录，构建删除条件并删除
                    for record in records_to_delete:
                        # 构建基于主键的删除条件（更通用的实现）
                        condition = {}
                        
                        # 尝试常见的主键字段
                        possible_keys = ['id', 'order_id', 'customer_id', 'emp_id', 'employee_id', 'dept_id', 'department_id', 'project_id']
                        for key in possible_keys:
                            if key in record:
                                condition[key] = record[key]
                                break
                        
                        # 如果没有找到主键，使用所有字段作为条件（确保精确匹配）
                        if not condition:
                            condition = dict(record)
                        
                        if condition:
                            deleted = self.storage_engine.delete_records(self.table_name, condition)
                            self.deleted_count += deleted
                else:
                    # 没有子执行器，直接解析WHERE条件
                    condition = {}
                    if self.where_condition:
                        condition = self._parse_where_condition(self.where_condition)
                    
                    # 尝试删除记录
                    self.deleted_count = self.storage_engine.delete_records(
                        self.table_name, condition
                    )
                    
                    # 如果没有删除任何记录，且条件中有数值，尝试用字符串类型再次匹配
                    if self.deleted_count == 0 and condition:
                        alternative_condition = self._create_alternative_condition(condition)
                        if alternative_condition and alternative_condition != condition:
                            print(f"[DELETE] 第一次匹配失败，尝试替代条件: {alternative_condition}")
                            self.deleted_count = self.storage_engine.delete_records(
                                self.table_name, alternative_condition
                            )
                
                result = {
                    "operation": "DELETE",
                    "table_name": self.table_name,
                    "deleted_rows": self.deleted_count,
                    "success": True,  # DELETE操作本身成功，即使删除行数为0
                    "message": f"Deleted {self.deleted_count} rows from '{self.table_name}'"
                }
            else:
                # 模拟执行
                self.deleted_count = 1  # 模拟删除1行
                result = {
                    "operation": "DELETE",
                    "table_name": self.table_name,
                    "deleted_rows": self.deleted_count,
                    "success": True,
                    "message": f"Deleted {self.deleted_count} rows from '{self.table_name}' (simulated)"
                }
            
            # 更新统计
            self.update_stats(rows_processed=self.deleted_count)
            
            yield result
            
        except Exception as e:
            print(f"[DELETE] 删除操作发生异常: {e}")
            print(f"[DELETE] 异常类型: {type(e).__name__}")
            print(f"[DELETE] 表名: {self.table_name}")
            print(f"[DELETE] WHERE条件: {self.where_condition}")
            import traceback
            traceback.print_exc()
            
            error_result = {
                "operation": "DELETE",
                "table_name": self.table_name,
                "deleted_rows": 0,
                "success": False,
                "error": f"{type(e).__name__}: {str(e)}"
            }
            yield error_result
    
    def close(self):
        """关闭DELETE操作符"""
        with self.lock:
            if not self.is_open:
                return
            
            self.is_open = False
            self.current_iterator = None
            
            # 更新最终统计
            self.stats.execution_time_ms = (time.time() - self.context.start_time) * 1000
    
    def get_estimated_cost(self) -> float:
        """获取估算成本"""
        return 1.5  # DELETE操作成本中等（查询+删除）
    
    def get_estimated_rows(self) -> int:
        """获取估算行数"""
        return 1  # DELETE操作返回1行结果（执行摘要）
    
    def _parse_where_condition(self, where_condition: str) -> Dict[str, Any]:
        """解析WHERE条件（支持多种比较操作符，包括LIKE）"""
        condition = {}
        try:
            # 处理LIKE操作符
            if ' LIKE ' in where_condition.upper():
                # 使用原始条件进行分割，保持字段名的原始大小写
                like_pos = where_condition.upper().find(' LIKE ')
                if like_pos != -1:
                    field = where_condition[:like_pos].strip()
                    pattern = where_condition[like_pos + 6:].strip().strip("'\"")
                    # 转换SQL LIKE模式为正则表达式
                    import re
                    regex_pattern = pattern.replace('%', '.*').replace('_', '.')
                    condition[field] = {"$regex": regex_pattern}
                    return condition
            
            # 支持的操作符，按长度降序排列以避免匹配冲突
            operators = ['>=', '<=', '!=', '=', '>', '<']
            
            for op in operators:
                if op in where_condition:
                    parts = where_condition.split(op, 1)  # 只分割第一个匹配
                    if len(parts) == 2:
                        field = parts[0].strip()
                        value = parts[1].strip().strip("'\"")
                        
                        # 尝试转换为数字
                        try:
                            value = int(value)
                        except ValueError:
                            try:
                                value = float(value)
                            except ValueError:
                                pass  # 保持字符串
                        
                        # 根据操作符构建存储引擎能理解的条件格式
                        if op == '=':
                            condition[field] = value
                        elif op == '>':
                            condition[field] = {"$gt": value}
                        elif op == '<':
                            condition[field] = {"$lt": value}
                        elif op == '>=':
                            condition[field] = {"$gte": value}
                        elif op == '<=':
                            condition[field] = {"$lte": value}
                        elif op == '!=':
                            condition[field] = {"$ne": value}
                        
                        break  # 找到第一个匹配的操作符就退出
                        
        except Exception as e:
            print(f"解析WHERE条件失败: {e}")
            import traceback
            traceback.print_exc()
        
        return condition
    
    def _create_alternative_condition(self, original_condition: Dict[str, Any]) -> Dict[str, Any]:
        """创建替代条件，用于处理数据类型不匹配的情况"""
        alternative_condition = {}
        
        for field, value in original_condition.items():
            # 如果是简单的等值条件，尝试转换数据类型
            if not isinstance(value, dict):  # 不是 {"$gt": ...} 这样的复杂条件
                if isinstance(value, int):
                    # 数字转字符串
                    alternative_condition[field] = str(value)
                elif isinstance(value, str) and value.isdigit():
                    # 纯数字字符串转整数
                    alternative_condition[field] = int(value)
                elif isinstance(value, str):
                    try:
                        # 尝试转换为浮点数
                        alternative_condition[field] = float(value)
                    except ValueError:
                        # 保持原值
                        alternative_condition[field] = value
                else:
                    # 其他类型保持原值
                    alternative_condition[field] = value
            else:
                # 复杂条件，尝试转换内部的值
                for op, op_value in value.items():
                    if isinstance(op_value, int):
                        alternative_condition[field] = {op: str(op_value)}
                    elif isinstance(op_value, str) and op_value.isdigit():
                        alternative_condition[field] = {op: int(op_value)}
                    else:
                        alternative_condition[field] = value
                    break  # 只处理第一个操作符
        
        return alternative_condition


class CreateDatabaseOperator(IteratorExecutor):
    """CREATE DATABASE操作符"""
    
    def __init__(self, executor_id: str, context: ExecutionContext,
                 database_name: str, charset: str = "utf8",
                 storage_engine: StorageEngineAdapter = None):
        super().__init__(executor_id, context)
        self.database_name = database_name
        self.charset = charset
        self.storage_engine = storage_engine
        self.executed = False
        self.success = False
    
    def open(self):
        """打开CREATE DATABASE操作符"""
        with self.lock:
            if self.is_open:
                return
            
            self.is_open = True
            self.current_iterator = self._create_database_iterator()
            
            # 更新统计信息
            self.update_stats(io_ops=1)
    
    def _create_database_iterator(self) -> Iterator[Record]:
        """创建数据库执行迭代器"""
        if self.executed:
            return
        
        self.executed = True
        
        try:
            print(f"[DEBUG CREATE_DB] 数据库名:{self.database_name}, 字符集:{self.charset}")
            
            if self.storage_engine and hasattr(self.storage_engine, 'db_adapter'):
                # 使用DatabaseServerAdapter创建数据库
                success = self.storage_engine.db_adapter.create_database(
                    self.database_name, self.charset
                )
                self.success = success
                print(f"[DEBUG CREATE_DB] 通过适配器创建数据库结果: {success}")
            else:
                print(f"[DEBUG CREATE_DB] 存储引擎不可用，模拟创建数据库")
                # 模拟执行
                self.success = True
            
            # 生成执行结果
            result = {
                "operation": "CREATE_DATABASE",
                "database_name": self.database_name,
                "charset": self.charset,
                "success": self.success,
                "message": f"Database '{self.database_name}' created successfully" if self.success 
                          else f"Failed to create database '{self.database_name}'"
            }
            
            # 更新统计
            self.update_stats(rows_processed=1 if self.success else 0)
            
            yield result
            
        except Exception as e:
            print(f"[DEBUG CREATE_DB] 创建数据库异常: {e}")
            result = {
                "operation": "CREATE_DATABASE",
                "database_name": self.database_name,
                "success": False,
                "error": str(e),
                "message": f"Failed to create database '{self.database_name}': {e}"
            }
            yield result
    
    def next(self) -> Optional[Record]:
        """获取下一条记录"""
        if not self.is_open:
            self.open()
        
        try:
            return next(self.current_iterator)
        except StopIteration:
            return None
    
    def close(self):
        """关闭操作符"""
        with self.lock:
            if not self.is_open:
                return
            
            self.is_open = False
            self.current_iterator = None
            
            # 更新统计信息
            self.stats.execution_time_ms = (time.time() - self.context.start_time) * 1000
    
    def get_estimated_rows(self) -> int:
        """获取估算行数"""
        return 1  # DDL操作返回1行结果


class DropDatabaseOperator(IteratorExecutor):
    """DROP DATABASE操作符"""
    
    def __init__(self, executor_id: str, context: ExecutionContext,
                 database_name: str, force: bool = False,
                 storage_engine: StorageEngineAdapter = None):
        super().__init__(executor_id, context)
        self.database_name = database_name
        self.force = force
        self.storage_engine = storage_engine
        self.executed = False
        self.success = False
    
    def open(self):
        """打开DROP DATABASE操作符"""
        with self.lock:
            if self.is_open:
                return
            
            self.is_open = True
            self.current_iterator = self._drop_database_iterator()
            
            # 更新统计信息
            self.update_stats(io_ops=1)
    
    def _drop_database_iterator(self) -> Iterator[Record]:
        """删除数据库执行迭代器"""
        if self.executed:
            return
        
        self.executed = True
        
        try:
            print(f"[DEBUG DROP_DB] 数据库名:{self.database_name}, 强制删除:{self.force}")
            
            if self.storage_engine and hasattr(self.storage_engine, 'db_adapter'):
                # 使用DatabaseServerAdapter删除数据库
                success = self.storage_engine.db_adapter.drop_database(
                    self.database_name, self.force
                )
                self.success = success
                print(f"[DEBUG DROP_DB] 通过适配器删除数据库结果: {success}")
            else:
                print(f"[DEBUG DROP_DB] 存储引擎不可用，模拟删除数据库")
                # 模拟执行
                self.success = True
            
            # 生成执行结果
            result = {
                "operation": "DROP_DATABASE",
                "database_name": self.database_name,
                "force": self.force,
                "success": self.success,
                "message": f"Database '{self.database_name}' dropped successfully" if self.success 
                          else f"Failed to drop database '{self.database_name}'"
            }
            
            # 更新统计
            self.update_stats(rows_processed=1 if self.success else 0)
            
            yield result
            
        except Exception as e:
            print(f"[DEBUG DROP_DB] 删除数据库异常: {e}")
            result = {
                "operation": "DROP_DATABASE",
                "database_name": self.database_name,
                "success": False,
                "error": str(e),
                "message": f"Failed to drop database '{self.database_name}': {e}"
            }
            yield result
    
    def next(self) -> Optional[Record]:
        """获取下一条记录"""
        if not self.is_open:
            self.open()
        
        try:
            return next(self.current_iterator)
        except StopIteration:
            return None
    
    def close(self):
        """关闭操作符"""
        with self.lock:
            if not self.is_open:
                return
            
            self.is_open = False
            self.current_iterator = None
            
            # 更新统计信息
            self.stats.execution_time_ms = (time.time() - self.context.start_time) * 1000
    
    def get_estimated_rows(self) -> int:
        """获取估算行数"""
        return 1  # DDL操作返回1行结果


class UseDatabaseOperator(IteratorExecutor):
    """USE DATABASE操作符"""
    
    def __init__(self, executor_id: str, context: ExecutionContext,
                 database_name: str, storage_engine: StorageEngineAdapter = None):
        super().__init__(executor_id, context)
        self.database_name = database_name
        self.storage_engine = storage_engine
        self.executed = False
        self.success = False
    
    def open(self):
        """打开USE DATABASE操作符"""
        with self.lock:
            if self.is_open:
                return
            
            self.is_open = True
            self.current_iterator = self._use_database_iterator()
            
            # 更新统计信息
            self.update_stats(io_ops=1)
    
    def _use_database_iterator(self) -> Iterator[Record]:
        """切换数据库执行迭代器"""
        if self.executed:
            return
        
        self.executed = True
        
        try:
            print(f"[DEBUG USE_DB] 数据库名:{self.database_name}")
            
            if self.storage_engine and hasattr(self.storage_engine, 'db_adapter'):
                # 使用DatabaseServerAdapter切换数据库
                success = self.storage_engine.db_adapter.use_database(self.database_name)
                self.success = success
                print(f"[DEBUG USE_DB] 通过适配器切换数据库结果: {success}")
            else:
                print(f"[DEBUG USE_DB] 存储引擎不可用，模拟切换数据库")
                # 模拟执行
                self.success = True
            
            # 生成执行结果
            result = {
                "operation": "USE_DATABASE",
                "database_name": self.database_name,
                "success": self.success,
                "message": f"Switched to database '{self.database_name}'" if self.success 
                          else f"Failed to switch to database '{self.database_name}'"
            }
            
            # 更新统计
            self.update_stats(rows_processed=1 if self.success else 0)
            
            yield result
            
        except Exception as e:
            print(f"[DEBUG USE_DB] 切换数据库异常: {e}")
            result = {
                "operation": "USE_DATABASE",
                "database_name": self.database_name,
                "success": False,
                "error": str(e),
                "message": f"Failed to switch to database '{self.database_name}': {e}"
            }
            yield result
    
    def next(self) -> Optional[Record]:
        """获取下一条记录"""
        if not self.is_open:
            self.open()
        
        try:
            return next(self.current_iterator)
        except StopIteration:
            return None
    
    def close(self):
        """关闭操作符"""
        with self.lock:
            if not self.is_open:
                return
            
            self.is_open = False
            self.current_iterator = None
            
            # 更新统计信息
            self.stats.execution_time_ms = (time.time() - self.context.start_time) * 1000
    
    def get_estimated_rows(self) -> int:
        """获取估算行数"""
        return 1  # DDL操作返回1行结果


class ListDatabasesOperator(IteratorExecutor):
    """LIST DATABASES操作符"""
    
    def __init__(self, executor_id: str, context: ExecutionContext,
                 storage_engine: StorageEngineAdapter = None):
        super().__init__(executor_id, context)
        self.storage_engine = storage_engine
        self.executed = False
        self.databases = []
    
    def open(self):
        """打开LIST DATABASES操作符"""
        with self.lock:
            if self.is_open:
                return
            
            self.is_open = True
            self.current_iterator = self._list_databases_iterator()
            
            # 更新统计信息
            self.update_stats(io_ops=1)
    
    def _list_databases_iterator(self) -> Iterator[Record]:
        """列出数据库执行迭代器"""
        if self.executed:
            return
        
        self.executed = True
        
        try:
            print(f"[DEBUG LIST_DB] 列出所有数据库")
            
            if self.storage_engine and hasattr(self.storage_engine, 'db_adapter'):
                # 使用DatabaseServerAdapter列出数据库
                databases = self.storage_engine.db_adapter.list_databases()
                self.databases = databases or []
                print(f"[DEBUG LIST_DB] 通过适配器获取数据库列表: {self.databases}")
            else:
                print(f"[DEBUG LIST_DB] 存储引擎不可用，返回默认数据库列表")
                # 模拟执行
                self.databases = ["default", "test_db"]
            
            # 生成执行结果 - 为每个数据库生成一条记录
            for db_name in self.databases:
                result = {
                    "database_name": db_name,
                    "operation": "LIST_DATABASES"
                }
                yield result
            
            # 如果没有数据库，返回一条提示记录
            if not self.databases:
                result = {
                    "database_name": None,
                    "operation": "LIST_DATABASES",
                    "message": "No databases found"
                }
                yield result
            
            # 更新统计
            self.update_stats(rows_processed=len(self.databases))
            
        except Exception as e:
            print(f"[DEBUG LIST_DB] 列出数据库异常: {e}")
            result = {
                "operation": "LIST_DATABASES",
                "success": False,
                "error": str(e),
                "message": f"Failed to list databases: {e}"
            }
            yield result
    
    def next(self) -> Optional[Record]:
        """获取下一条记录"""
        if not self.is_open:
            self.open()
        
        try:
            return next(self.current_iterator)
        except StopIteration:
            return None
    
    def close(self):
        """关闭操作符"""
        with self.lock:
            if not self.is_open:
                return
            
            self.is_open = False
            self.current_iterator = None
            
            # 更新统计信息
            self.stats.execution_time_ms = (time.time() - self.context.start_time) * 1000
    
    def get_estimated_rows(self) -> int:
        """获取估算行数"""
        return len(self.databases) if self.databases else 1  # 返回数据库数量或至少1行


class CreateUserOperator(IteratorExecutor):
    """CREATE USER操作符"""
    
    def __init__(self, executor_id: str, context: ExecutionContext,
                 username: str, password: Optional[str] = None,
                 storage_engine: StorageEngineAdapter = None):
        super().__init__(executor_id, context)
        self.username = username
        self.password = password
        self.storage_engine = storage_engine
        self.executed = False
        self.success = False
    
    def open(self):
        """打开CREATE USER操作符"""
        with self.lock:
            if self.is_open:
                return
            
            self.is_open = True
            iterator = self._create_user_iterator()
            # 如果生成器返回None（已执行情况），创建空迭代器
            self.current_iterator = iterator if iterator is not None else iter([])
            
            # 更新统计信息
            self.update_stats(io_ops=1)
    
    def _create_user_iterator(self) -> Iterator[Record]:
        """创建用户创建执行迭代器"""
        # 对于生成器函数，如果已执行，直接返回（生成器将为空）
        if self.executed:
            return
        
        self.executed = True
        
        try:
            if self.storage_engine and hasattr(self.storage_engine, 'db_adapter'):
                # 使用存储引擎的用户管理功能
                success = self.storage_engine.db_adapter.create_user(self.username, self.password)
                self.success = success
                
                result = {
                    "operation": "CREATE USER",
                    "username": self.username,
                    "success": success,
                    "message": f"User '{self.username}' created successfully" if success 
                              else f"Failed to create user '{self.username}'"
                }
            else:
                # 模拟创建用户
                self.success = True
                result = {
                    "operation": "CREATE USER",
                    "username": self.username,
                    "success": True,
                    "message": f"User '{self.username}' created (simulated)"
                }
            
            self.update_stats(rows_processed=1)
            yield result
            
        except Exception as e:
            self.success = False
            error_result = {
                "operation": "CREATE USER",
                "username": self.username,
                "success": False,
                "message": f"Failed to create user '{self.username}': {str(e)}",
                "error": str(e)
            }
            yield error_result
    
    def next_batch(self, batch_size: int = 1000) -> Optional[RecordBatch]:
        """获取下一批记录"""
        if not self.is_open:
            return None
        
        batch = []
        for _ in range(batch_size):
            # 如果迭代器已经为None，直接跳出
            if self.current_iterator is None:
                break
            try:
                record = next(self.current_iterator)
                batch.append(record)
            except StopIteration:
                self.current_iterator = None
                break
        
        if batch:
            return batch
        else:
            return None
    
    def close(self):
        """关闭操作符"""
        with self.lock:
            if not self.is_open:
                return
            
            self.is_open = False
            self.current_iterator = None
            
            # 更新统计信息
            self.stats.execution_time_ms = (time.time() - self.context.start_time) * 1000
    
    def get_estimated_rows(self) -> int:
        """获取估算行数"""
        return 1  # CREATE USER操作总是返回1行结果


class DropUserOperator(IteratorExecutor):
    """DROP USER操作符"""
    
    def __init__(self, executor_id: str, context: ExecutionContext,
                 username: str, storage_engine: StorageEngineAdapter = None):
        super().__init__(executor_id, context)
        self.username = username
        self.storage_engine = storage_engine
        self.executed = False
        self.success = False
    
    def open(self):
        """打开DROP USER操作符"""
        with self.lock:
            if self.is_open:
                return
            
            self.is_open = True
            iterator = self._create_drop_user_iterator()
            # 如果生成器返回None（已执行情况），创建空迭代器
            self.current_iterator = iterator if iterator is not None else iter([])
            
            # 更新统计信息
            self.update_stats(io_ops=1)
    
    def _create_drop_user_iterator(self) -> Iterator[Record]:
        """创建删除用户执行迭代器"""
        # 对于生成器函数，如果已执行，直接返回（生成器将为空）
        if self.executed:
            return
        
        self.executed = True
        
        try:
            if self.storage_engine and hasattr(self.storage_engine, 'db_adapter'):
                # 使用存储引擎的用户管理功能
                success = self.storage_engine.db_adapter.drop_user(self.username)
                self.success = success
                
                result = {
                    "operation": "DROP USER",
                    "username": self.username,
                    "success": success,
                    "message": f"User '{self.username}' dropped successfully" if success 
                              else f"Failed to drop user '{self.username}'"
                }
            else:
                # 模拟删除用户
                self.success = True
                result = {
                    "operation": "DROP USER",
                    "username": self.username,
                    "success": True,
                    "message": f"User '{self.username}' dropped (simulated)"
                }
            
            self.update_stats(rows_processed=1)
            yield result
            
        except Exception as e:
            self.success = False
            error_result = {
                "operation": "DROP USER",
                "username": self.username,
                "success": False,
                "message": f"Failed to drop user '{self.username}': {str(e)}",
                "error": str(e)
            }
            yield error_result
    
    def next_batch(self, batch_size: int = 1000) -> Optional[RecordBatch]:
        """获取下一批记录"""
        if not self.is_open:
            return None
        
        batch = []
        for _ in range(batch_size):
            # 如果迭代器已经为None，直接跳出
            if self.current_iterator is None:
                break
            try:
                record = next(self.current_iterator)
                batch.append(record)
            except StopIteration:
                self.current_iterator = None
                break
        
        if batch:
            return batch
        else:
            return None
    
    def close(self):
        """关闭操作符"""
        with self.lock:
            if not self.is_open:
                return
            
            self.is_open = False
            self.current_iterator = None
            
            # 更新统计信息
            self.stats.execution_time_ms = (time.time() - self.context.start_time) * 1000
    
    def get_estimated_rows(self) -> int:
        """获取估算行数"""
        return 1  # DROP USER操作总是返回1行结果